<?php
include 'dbconfig.php';
include 'opendb.php';
if (isset($_POST['action']) && $_POST['action']=='insert') {
	$name = $_POST['name'];
	$title = $_POST['title'];
	$path = $_POST['path'];
	$type = $_POST['type'];
	$cID = $_POST['cID'];
	$pID = $_POST['pID'];
	$des = $_POST['des'];
	//$name = $_SESSION["assetName"];
	//$fullpath=$path.$name;
	//echo 'path is:'.$path;
	//echo 'full path is: '.$fullpath;
	$result=  insertAsset($name, $title, $type, $path, $cID , $pID, $des);
	echo $result;
}

function insertAsset ($name, $title, $type, $path, $cID , $pID, $des) {
	$fullAssetPath=$path.$name;
	return mysql_query("INSERT INTO wp_asset(RES_NAME, RES_TITLE, RES_TYPE, RES_PATH, IS_DELETED, contributor_ID, project_ID, description)
        	VALUES('".cleanAssetAndroidInput($name)."','".cleanAssetAndroidInput($title)."','$type','$fullAssetPath','0','$cID','$pID','".cleanAssetAndroidInput($des)."')");
}
if (isset($_GET['action']) && $_GET['action']=='upload') {
	echo $_FILES["uploadedfile"]["name"];
	echo $_FILES["uploadedfile"]["type"];
	$target_path = basename( $_FILES["uploadedfile"]["name"]);
	if(upload_asset()) {
		echo "The file ".basename( $_FILES["uploadedfile"]["name"])." has been uploaded";
	} else{
		echo "There was an error uploading the file, please try again!";
	}
}




/**
 *
 * Upload asset to the server
 * @param	string	mode of the upload eg; new or replace
 *
 */
function upload_asset() {
	// Below lines are to display file name, temp name and file type , you can use them

	//for testing your script only//////
	//echo "File Name: ".$_FILES[flUserfile][name]."<br>";
	//cho "tmp name: ".$_FILES[flUserfile][tmp_name]."<br>";
	//echo "File Type: ".$_FILES[flUserfile][type]."<br>";
	//echo "<pre>";
	//print_r($_FILES);
	//echo "</pre>";
	$resTypeArr = explode(".",$_FILES[uploadedfile][name]);

	$resType = "";
	$tempResType = $resTypeArr[sizeof($resTypeArr)-1];
	echo "typeeeeeeeeeeeeee: ".$tempResType;
	echo "resFull path is: ".getcwd();

	if(strtoupper($tempResType) == "3GP") {
		$resType = "audio";
	}
	else if((strtoupper($tempResType) == "MP4") || (strtoupper($tempResType) == "M4A")) {
		$resType = "video";
	}
	else if((strtoupper($tempResType) == "JPG") || (strtoupper($tempResType) == "JPEG")) {
		$resType = "image";
	}

	$resName = $_FILES[uploadedfile][name];
	$resFullPath=$_SERVER["DOCUMENT_ROOT"]."wordpress/assets/".$resType."/".$resName; // the path with the file name where
	
	setcookie("resFullPath", $resName, $expire);

	echo "resFull path is: ".$resFullPath;
	//the file will be stored, upload is the directory name.

	if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $resFullPath)){
		if($type=='image') {
		$imagePath = 'assets/image/'.$resName;
			generate_thumbnail($imagePath, $resName);
		}		
	}
	else{
		?>
	<script type="text/javascript">
		alert("Failed to upload file Contact Site admin to fix the problem");
		</script>
		<?php
		return false;
	}
}


/**
 *
 * Sanitize Database Inputs
 * @param	string	input applying sanitize
 *
 */
function cleanAssetAndroidInput($input) {

	$search = array(
    '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
    '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
    '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
    '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
	);

	$output = preg_replace($search, '', $input);
	return $output;
}

/**
 *
 * Generate thumbnail for images and videos
 * @param	string resource relative path
 * @param	string resiurce name
 *
 */
function generate_thumbnail($resFullPath, $resName) {
	///////// Start the thumbnail generation//////////////
	$n_width=75; // Fix the width of the thumb nail images
	$n_height=75; // Fix the height of the thumb nail imaage

	$tsrc="assets/thumbnail/".$resName; // Path where thumb nail image will be stored
	$ggg =  $_FILES[uploadedfile][type];
	//echo $ggg;
	/*
	 if (!($_FILES[userfile][type] =="image/jpeg" OR $_FILES[userfile][type]

	 =="image/gif")){
		echo "Your uploaded file must be of JPG or GIF. Other file types are not

		allowed<BR>";
		exit;
		}
		*/
		
	////////////// starting of JPG thumb nail creation//////////
		$im=ImageCreateFromJPEG($resFullPath);
		$width=ImageSx($im); // Original picture width is stored
		$height=ImageSy($im); // Original picture height is stored
		$newImage=imagecreatetruecolor($n_width,$n_height);
		imageCopyResized($newImage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
		ImageJpeg($newImage,$tsrc);
		//chmod("$tsrc",0777);
	

	if(strlen(strpos($resType, "video"))>0) {
		echo "<script type='text/javascript'>";
		//echo "alert(getcwd())";
		echo "</script>";

		// movie.avi.... name of the movie you want to take a screenshot from
		// 00:00:00.... Where in the movie do you wanna take your screenshot, 10

		//seconds from start? ex: 00:00:10
		// picname..... name your generated pic
		//echo "video file done";
		$inputPath = getcwd()."\\assets\\video\\";
		$outputPath = getcwd()."\\assets\\thumbnail\\";
		$arrFileComp = explode(".", $resName);
		$fileName = "";
		for($index=0; $index<sizeof($arrFileComp)-1; $index++) {
			$fileName .= $arrFileComp[$index];
		}
		$inputVideoName = $inputPath.$resName;
		$thumbnailName = $outputPath.$fileName.".png";
		//echo $inputVideoName."********************".$thumbnailName."<br/>";
		convertToFlv($inputVideoName, $thumbnailName);
		//exec("START c:\ffmpeg\bin\ffmpeg -vcodec png -i

		//C:\wamp\www\wordpress\assets\video\__Coca_Cola_mix1.mpeg -ss  00:00:03 -vframes frames

		//test1%d.png");

	}
	////////// end of jpeg file thumb nail creation//////////
}



function convertToFlv($input, $output) {
	$pathToFfmpeg = get_option("ffmpegPath");
	//$pathToFfmpeg = "c:\\ffmpeg\\bin\\";
	//$shell = new COM("WScript.Shell") or die("Requires Windows Scripting Host");
	//$devenvpath=$shell->RegRead("HKEY_CLASSES_ROOT\\Local

	//Settings\\SOFTWARE\\Microsoft\\Windows\\shell\\muicache\\");
	// echo "Converting $input to $output<br />";
	$command = $pathToFfmpeg." -v 0 -y -i $input -vframes 1 -ss 2 -vcodec mjpeg -f rawvideo -s 75x75 -aspect 16:9 $output ";
	// echo "$command<br />";
	shell_exec( $command );
	// echo "Converted<br />";
}

?>